import { unique } from '@/utils/string.js'
import { mapGetters } from 'vuex'
import storage from '@/utils/storage'

// #ifdef MP-WEIXIN
import { Base64 } from "js-base64";
import { pathToBase64 } from 'image-tools'

// #endif

let cos = null
let fileKey = null
// #ifdef H5

fileKey = 'Body'
// #endif

// #ifdef MP-WEIXIN

fileKey = 'FilePath'
// #endif

export function uploadFile(fileData, opts) {
	console.log('fileData===================', fileData)
	let currentUser=storage.get('STORAGE_CURRENT_USER')

	if (!cos) {
		throw new Error('未实例话对象存储')
	}
	opts = Object.assign({
		onProgress: null
	}, opts)
	return new Promise((resolve, reject) => {
		const uploadValue = fileKey === 'Body' ? fileData.file : fileData.path
		console.log('uploadValue===================', uploadValue)

		const uploadParam = {}
		const endName= getFileExtension(uploadValue)
		uploadParam[fileKey] = uploadValue
		// 执行上传操作
		cos.putObject(Object.assign({
			Bucket: 'aiduk-1334050802', // 存储桶
			Region: 'ap-guangzhou', // 地域
			Key: '/ztc/weapp/'+currentUser.userId +'/'+ unique() + '.'+endName, // 文件名
			StorageClass: 'STANDARD', // 上传的模式类型 直接默认 标准模式即可
			onProgress: (progressData) => {
				if (opts && opts.onProgress) {
					opts.onProgress({
						percent: progressData.percent * 100
					})
				}
			},
		}, uploadParam), (err, data) => {
			if (err) {
				reject(err)
			} else {
				resolve({
					path: data.Location
				})
			}
		})
	})
}

export const uploadFileToTencentClound = (filename, filePath, localtions) => {
	uni.showLoading({
		title: '上传中'
	});
	// 如果是视频且需要压缩，调用服务端视频压缩接口
/*	if (params.videoQuality && isVideo(filePath)) {
		// 调用服务端视频压缩接口
		return serverVideoCompress(filePath, {
			quality: params.videoQuality,
			maxDuration: params.maxDuration
		});
	}*/
	let currentUser = storage.get('STORAGE_CURRENT_USER')
	console.log("uploadFileToTencentClound=================", filename, filePath)

	let nowWeek = ''
	let yy = new Date().getFullYear()
	let mm = new Date().getMonth() + 1
	let dd = new Date().getDate()
	let week = new Date().getDay()
	let hh = new Date().getHours()
	let ms = new Date().getSeconds() < 10 ? "0" + new Date().getSeconds() : new Date().getSeconds()
	let mf = new Date().getMinutes() < 10 ? "0" + new Date().getMinutes() : new Date().getMinutes()

	if (week == 1) {
		nowWeek = "星期一"
	} else if (week == 2) {
		nowWeek = "星期二"
	} else if (week == 3) {
		nowWeek = "星期三"
	} else if (week == 4) {
		nowWeek = "星期四"
	} else if (week == 5) {
		nowWeek = "星期五"
	} else if (week == 6) {
		nowWeek = "星期六"
	} else {
		nowWeek = "星期日"
	}

	if(!localtions){
		localtions = ''
	}

	let fileNae = unique() + '.' + getFileExtension(filePath)
	filename = '/ztc/weapp/' + currentUser.userId + '/' + fileNae
	let nowTime = "照片上传地区所在时间：\n" + yy + "年" + mm + "月" + dd + "日 " + " " + hh + "时" + mf + "分" + ms + "秒";
	let waterPicId = fileNae

	const rules = {
		is_pic_info: 1,
		rules: [
			{
				fileid: waterPicId,
				rule: "watermark/2/text/" + Base64.encodeURL(nowTime)
					+ "/fontsize/30/dissolve/90/gravity/southwest/dx/10/dy/15/fill/" + Base64.encodeURL('#ef133c')
			}
		]
	}

	// 判断是否为图片文件，只有图片才添加水印
	const isImage = /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(filePath);

	// 对于大文件使用分片上传
	const wxfs = wx.getFileSystemManager()

	return new Promise((resolve, reject) => {
		// 获取文件信息
		wxfs.getFileInfo({
			filePath: filePath,
			success: function(infoRes) {
				const fileSize = infoRes.size;
				console.log('文件大小:', (fileSize / 1024 / 1024).toFixed(2) + 'MB');

				// 对于大于5MB的文件使用分片上传
				if (fileSize > 5 * 1024 * 1024) {
					console.log('使用分片上传');

					const uploadOptions = {
						Bucket: 'aiduk-1334050802',
						Region: 'ap-guangzhou',
						Key: filename,
						FilePath: filePath,
						onProgress: function(progressData) {
							console.log('上传进度:', progressData.percent * 100 + '%');
						}
					};

					// 只有图片才添加水印
					if (isImage) {
						uploadOptions.Headers = {
							'Pic-Operations': JSON.stringify(rules)
						};
					}

					// 使用分片上传支持大文件
					cos.sliceUploadFile(uploadOptions, (err, data) => {
						uni.hideLoading();
						if (err) {
							console.log("分片上传错误:", JSON.stringify(err));
							reject(new Error('上传失败: ' + (err.message || '未知错误')));
						} else {
							console.log("分片上传成功:", JSON.stringify(data));
							let loca = data.Location || `https://aiduk-1334050802.cos.ap-guangzhou.myqcloud.com${filename}`;
							let result = {
								path: loca
							};
							resolve(result);
						}
					});
				} else {
					// 小文件使用普通上传
					console.log('使用普通上传');
					wxfs.readFile({
						filePath: filePath,
						success: function (res) {
							const uploadParams = {
								Bucket: 'aiduk-1334050802',
								Region: "ap-guangzhou",
								Key: filename,
								Body: res.data
							};

							// 只有图片才添加水印
							if (isImage) {
								uploadParams.Headers = {
									'Pic-Operations': JSON.stringify(rules)
								};
							}

							cos.putObject(uploadParams, (err, data) => {
								uni.hideLoading();
								if (err) {
									reject(new Error('上传失败: ' + (err.message || '未知错误')));
								} else {
									let loca = data.Location || `https://aiduk-1334050802.cos.ap-guangzhou.myqcloud.com${filename}`;
									let result = {
										path: loca
									};
									resolve(result);
								}
							});
						},
						fail: (readErr) => {
							uni.hideLoading();
							reject(new Error('读取文件失败'));
						}
					});
				}
			},
			fail: (infoErr) => {
				uni.hideLoading();
				console.error("获取文件信息失败:", infoErr);
				reject(new Error('获取文件信息失败'));
			}
		});
	});
}

export function getFileExtension(fileName) {
	const lastDotIndex = fileName.lastIndexOf('.');
	if (lastDotIndex === -1) {
		return ''; // 如果没有找到点号，返回空字符串
	}
	return fileName.slice(lastDotIndex + 1).toLowerCase();
}
